package alingrad.engine.core;

import javax.microedition.khronos.opengles.GL10;

import alingrad.engine.graphics.RenderManager;
import alingrad.engine.objects.MainLoop;
import alingrad.engine.util.TextureLoader;
import android.content.Context;

public class Game {
	private boolean mReady;
	private boolean mRunning;
	private boolean mPaused;
	private boolean mPrepared;
	private boolean mLoaded;
	private GameThread mThread;

	private Context mContext;

	private long mLastTimeMs;

	private final MainLoop mHead;

	public static RenderManager sRenderManager;
	public static ResourceLibrary sResourceLibrary;

	public Game(final MainLoop head, Context context) {
		mReady = false;
		mRunning = true;
		mPaused = false;
		mPrepared = false;
		mLoaded = false;

		mContext = context;
		mHead = head;
		sResourceLibrary = new ResourceLibrary();

		mThread = new GameThread();
		mThread.start();
	}

	private class GameThread extends Thread {

		public GameThread() {
			setName("Game Thread");
		}

		public void run() {
			while (!mReady) {
			}
			mLastTimeMs = System.currentTimeMillis();
			while (mRunning) {
				if (mPaused) {
					try {
						sleep(100);
					} catch (InterruptedException ex) {
					}
				} else {
					final long time = System.currentTimeMillis();
					final long delta = time - mLastTimeMs;
					mHead.update(delta);
					sRenderManager.sync();
					mLastTimeMs = time;
				}
			}
		}
	}

	public void start() {
		mReady = true;
	}

	public void pause() {
		mPaused = true;
	}

	public void resume() {
		mPaused = false;
		mLastTimeMs = System.currentTimeMillis();
	}

	public void stop() {
		mRunning = false;
	}

	public boolean isPrepared() {
		return mPrepared;
	}

	public boolean isLoaded() {
		return mLoaded;
	}

	public void loadGraphics(final GameRenderer renderer, GL10 gl) {
		sRenderManager = new RenderManager(renderer);
		TextureLoader.prepare(mContext);
		mHead.loadGraphics(gl);
		mPrepared = true;
		System.gc();
	}

	public void load() {
		mHead.load();
		mLoaded = true;
		System.gc();
	}
}
